
/*
 * Copyright (C) 2010 Bitglue. All rights reserved.
 *
 * $Id: AdminUserDAOImpl.java bself $
 */

package com.bitglue.hibernate.dao.impl;

import com.bitglue.hibernate.dao.AdminUserDAO;
import com.bitglue.hibernate.model.AdminUser;

import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * AdminUserDAOImpl is the Hibernate implementation
 * of the {@link AdminUserDAO} interface.
 * @author Bryan Patrick Self
 */
// @Component("adminUserDAOImpl")
@Repository("adminUserDAOImpl")
public class AdminUserDAOImpl implements AdminUserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    /**
     * getAdminUsers() returns a Collection of {@link AdminUsers}.
     */
    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public Collection<AdminUser> getAdminUsers() {
        Session s = sessionFactory.getCurrentSession();
        return s.createQuery("from AdminUser").list();
    }

    /**
     * getAdminUserById() returns a {@link AdminUser} by id.
     */
    @Transactional(readOnly = true)
    public AdminUser getAdminUserById(int id) {
        Session s = sessionFactory.getCurrentSession();
        return (AdminUser)s.get(AdminUser.class, id);
    }

    /**
     * getAdminUserByName() returns a {@link AdminUser} by name.
     */
    @Transactional(readOnly = true)
    public AdminUser getAdminUserByName(String username) {
        Session s = sessionFactory.getCurrentSession();
        String query = "from AdminUser s where s.username='"
          + username + "'";
        for (Object o :  s.createQuery(query).list())
            return (AdminUser)o;
        return null;
    }

    /**
     * storeAdminUser() persists {@link AdminUser}.
     */
    public void storeAdminUser(AdminUser user) {
        sessionFactory.getCurrentSession().merge(user);
    }

    /**
     * deleteAdminUserById() deletes a {@link AdminUser} by id.
     */
    public void deleteAdminUserById(int id) {
        Session s = sessionFactory.getCurrentSession();
        AdminUser user = getAdminUserById(id);
        if (user != null)
            s.delete(user);
    }

    /**
     * deleteAdminUser() deletes a {@link AdminUser}.
     */
    public void deleteAdminUser(AdminUser user) {
        deleteAdminUserById(user.getId());
    }

}
